//
//  FZAdvertisementView.m
//  KidDubbing
//
//  Created by Victor Ji on 16/8/29.
//  Copyright © 2016年 Feizhu Tech. All rights reserved.
//

#import "FZAdvertisementView.h"
#import <Masonry/Masonry.h>
#import "FZAdvertisementModel.h"

@interface FZAdvertisementView ()

@property (strong, nonatomic) UIImageView *imageView;
@property (strong, nonatomic) FZAdvertisementService *service;
@property (strong, nonatomic) FZAdvertisementModel *model;

@end

@implementation FZAdvertisementView

- (instancetype)init {
    self = [super init];
    if (self) {
        [self setup];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setup];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame type:(FZAdsType)type {
    self = [super initWithFrame:frame];
    if (self) {
        [self setup];
        self.type = type;
    }
    return self;
}

- (void)setup {
    self.type = FZAdsTypeLaunch;
    
    self.imageView = [[UIImageView alloc] initWithFrame:CGRectZero];
    self.imageView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tgr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [self.imageView addGestureRecognizer:tgr];
    [self addSubview:self.imageView];
    [self.imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self);
    }];
    
    self.service = [[FZAdvertisementService alloc] init];
}

- (void)didMoveToSuperview {
    [self requestAdsData];
}

- (void)requestAdsData {
    WEAKSELF
    [FZAdvertisementService getAdsWithType:self.type success:^(NSInteger statusCode, NSString *message, id responseDataObject) {
        STRONGSELFFor(weakSelf)
        if (statusCode == kFZRequestStatusCodeSuccess) {
            NSArray *models = responseDataObject;
            FZAdvertisementModel *model = [models firstObject];
            strongSelf.model = model;
            [strongSelf.imageView sd_setImageWithURL:[NSURL URLWithString:model.imageUrlString]];
        }
    } failure:^(id responseObject, NSError *error) {
        // do nothing
    }];
}

- (void)tapAction:(UITapGestureRecognizer *)tgr {
    [self dismiss];
    if (self.tapAdsBlock) {
        if (self.model.tintUrlString && ![self.model.tintUrlString isEqualToString:@""]) {
            self.tapAdsBlock(YES, self.model.tintUrlString, self.model.title, [self.model.isShare boolValue], self.model.shareImageUrlString, self.model.content);
        } else {
            self.tapAdsBlock(NO, self.model.html, self.model.title, [self.model.isShare boolValue], self.model.shareImageUrlString, self.model.content);
        }
    }
}

- (void)showInView:(UIView *)view {
    [view addSubview:self];
}

- (void)dismiss {
    [self removeFromSuperview];
}

@end
